﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using Aga.GestionDeArchivos.Domain.Entities;
using System.Data.Objects;

namespace Aga.GestionDeArchivos.Storage
{
    public class RoleRepository : RepositoryBase<Role>
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="RoleRepository"/> class.
        /// </summary>
        /// <param name="context">The context.</param>
        public RoleRepository(AgaEntities context)
            : base(context) { }

        /// <summary>
        /// Adds to context.
        /// </summary>
        /// <param name="entity">The entity.</param>
        /// <returns></returns>
        protected override Action<Role> AddToContext(Role entity)
        {
            return delegate { Context.AddToRoles(entity); };
        }

        /// <summary>
        /// Gets the entity set.
        /// </summary>
        /// <value>The entity set.</value>
        protected override ObjectSet<Role> EntitySet
        {
            get { return Context.Roles; }
        }


        /// <summary>
        /// Adds the actions to role.
        /// </summary>
        /// <param name="roleId">The role id.</param>
        /// <param name="actionsIds">The actions.</param>
        /// <returns></returns>
        public Role AddActionsToRole(int roleId, int[] actionsIds)
        {
            Role role = GetById(roleId);

            foreach (int action in actionsIds)
            {
                RoleAction newAction = RoleAction.CreateRoleAction(action, roleId);

                role.Actions.Add(newAction);
            }

            Save(role);

            return role;
        }

        /// <summary>
        /// Removes the actions from role.
        /// </summary>
        /// <param name="roleId">The role id.</param>
        /// <param name="actionsIds">The actions ids.</param>
        /// <returns></returns>
        public Role RemoveActionsFromRole(int roleId, int[] actionsIds)
        {
            Role role = GetById(roleId);

            actionsIds = actionsIds.Where(a => a != 0).ToArray();

            RoleAction[] actions = role.Actions.Where(a => actionsIds.Contains(a.ActionId)).ToArray();

            foreach (var action in actions)
                role.Actions.Remove(action);

            Save(role);

            return role;
        }

        /// <summary>
        /// Gets the roles by id.
        /// </summary>
        /// <param name="rolesId">The roles id.</param>
        /// <returns></returns>
        public IQueryable<Role> GetById(int[] rolesId)
        {
            var roles = from r in EntitySet
                        where rolesId.Contains(r.Id)
                        select r;

            return roles;
        }
    }
}
